package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.SalesOrdersQueryDTO;
import com.intelligent.mapper.SalesOrdersMapper;
import com.intelligent.pojo.PurchaseSupplier;
import com.intelligent.pojo.Product;
import com.intelligent.pojo.Unit;
import com.intelligent.pojo.SalesOrders;
import com.intelligent.pojo.TUser;
import com.intelligent.service.SalesOrdersService;
import com.intelligent.service.PurchaseSupplierService;
import com.intelligent.service.ProductService;
import com.intelligent.service.UnitService;
import com.intelligent.service.TUserService;
import com.intelligent.vo.SalesOrdersVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
* 针对表【sales_orders(销售订单表)】的数据库操作Service实现
*/
@Service
public class SalesOrdersServiceImpl extends ServiceImpl<SalesOrdersMapper, SalesOrders>
    implements SalesOrdersService{

    @Autowired
    private PurchaseSupplierService purchaseSupplierService;

    @Autowired
    private TUserService userService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UnitService unitService;

    @Override
    public Page<SalesOrdersVO> pageList(SalesOrdersQueryDTO queryDTO) {
        Page<SalesOrders> page = new Page<>(
            queryDTO.getPageNum() != null ? queryDTO.getPageNum() : 1,
            queryDTO.getPageSize() != null ? queryDTO.getPageSize() : 10
        );

        LambdaQueryWrapper<SalesOrders> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
            wrapper.like(SalesOrders::getOrderNo, queryDTO.getKeyword());
        }

        if (queryDTO.getOrderStatus() != null) {
            wrapper.eq(SalesOrders::getOrderStatus, queryDTO.getOrderStatus());
        }

        if (queryDTO.getStartDate() != null) {
            wrapper.ge(SalesOrders::getOrderDate, queryDTO.getStartDate());
        }
        if (queryDTO.getEndDate() != null) {
            wrapper.le(SalesOrders::getOrderDate, queryDTO.getEndDate());
        }

        // 根据产品名称模糊（通过先查产品再in过滤）
        if (StringUtils.isNotBlank(queryDTO.getProductName())) {
            java.util.List<Product> products = productService.lambdaQuery()
                .like(Product::getProductName, queryDTO.getProductName()).list();
            if (products != null && !products.isEmpty()) {
                java.util.Set<Long> ids = new java.util.HashSet<>();
                for (Product p : products) { if (p.getProductId() != null) ids.add(p.getProductId()); }
                if (!ids.isEmpty()) {
                    wrapper.in(SalesOrders::getProductId, ids);
                } else {
                    // 没有匹配产品，直接返回空页
                    return new Page<>(page.getCurrent(), page.getSize());
                }
            } else {
                return new Page<>(page.getCurrent(), page.getSize());
            }
        }

        IPage<SalesOrders> result = this.page(page, wrapper);

        return (Page<SalesOrdersVO>) result.convert(item -> {
            SalesOrdersVO vo = new SalesOrdersVO();
            BeanUtils.copyProperties(item, vo);

            if (item.getCustomerId() != null) {
                PurchaseSupplier supplier = purchaseSupplierService.getById(item.getCustomerId());
                if (supplier != null) {
                    vo.setSupplierName(supplier.getSupplierName());
                }
            }

            if (item.getUId() != null) {
                TUser user = userService.getById(item.getUId());
                if (user != null) {
                    vo.setUserName(user.getUsername());
                }
            }

            if (item.getProductId() != null) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    vo.setProductId(product.getProductId());
                    vo.setProductName(product.getProductName());
                    vo.setProductCode(product.getProductCode());
                    if (product.getUnitId() != null) {
                        Unit unit = unitService.getById(product.getUnitId());
                        if (unit != null) {
                            vo.setUnitName(unit.getUnitName());
                        }
                    }
                }
            }

            return vo;
        });
    }

    @Override
    public boolean addOrder(SalesOrders entity) {
        if (entity == null) {
            throw new IllegalArgumentException("新增数据不能为空");
        }

        if (entity.getUId() == null) {
            throw new IllegalArgumentException("负责销售(uId)不能为空");
        }

        if (StringUtils.isBlank(entity.getOrderNo())) {
            entity.setOrderNo(generateOrderNo());
        }

        return this.save(entity);
    }

    private String generateOrderNo() {
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        int random = 1000 + new Random().nextInt(9000);
        return "XSDD" + dateStr + random;
    }
}




